package epoch.game.core.netty;

import epoch.game.core.config.ServerConfig;
import epoch.game.core.exception.SysException;
import epoch.game.core.server.Server;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.WriteBufferWaterMark;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public abstract class NettyServer extends Server {
	
	protected NettyServer(String configFilePath) {
		super(ServerConfig.load(configFilePath));
	}

	protected NettyServer(ServerConfig config) {
		super(config);
	}

	protected void init() {
		super.init();
	}
	
	@Override
	public void start() {
		EventLoopGroup bossGroup = new NioEventLoopGroup();
		EventLoopGroup workerGroup = new NioEventLoopGroup(Math.max(1, Runtime.getRuntime().availableProcessors() / 2));
		try {
			// 启动netty监听
			ServerBootstrap b = new ServerBootstrap();
			b.group(bossGroup, workerGroup)
					.channel(NioServerSocketChannel.class)
					.option(ChannelOption.SO_BACKLOG, 10240)
					.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)		//使用内存池
					.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)	//使用内存池
					.childOption(ChannelOption.TCP_NODELAY, true)
					.childOption(ChannelOption.SO_KEEPALIVE, true)
					.childOption(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(128 * 1024, 256 * 1024)) //输出流量水位控制
					.childHandler(new ChannelInitializer<SocketChannel>() {
						@Override
						public void initChannel(SocketChannel ch) throws Exception {
							ChannelPipeline p = ch.pipeline();
							p.addLast(new Decoder(10240), new Encoder(), new ServerHandler());
						}
					});

			//启动
			Channel ch = b.bind(this.serverConfig.getPort()).sync().channel();
			ch.closeFuture().sync();
		} catch (Exception e) {
			throw new SysException(e);
		} finally {
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
	}

}
